package com.turkcell.dv.rest;

import java.util.Calendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.eolcum.evocenter.Action;
import com.eolcum.evocenter.ActionBuffer;
import com.google.gson.Gson;
import com.turkcell.dv.rest.dto.PollDTO;

@RestController
@RequestMapping(value = "/pollingService", headers = "Content-Type=application/json", produces = "application/json")
public class PollingService {
	
	@Autowired private ActionBuffer buffer;
	private final Long pollEndingInterval = new Long(600000L);
	
	@RequestMapping(value= "/poll", method = RequestMethod.POST)
	@ResponseBody
	public String poll(@RequestBody String evoId) {
		Gson gson = new Gson();
		PollDTO pollDTO = new PollDTO();
		pollDTO.setFrequency(5000L);
		if(buffer.getActionMap().size() > 0) {
			List<Action> actionList = buffer.getActionList(evoId);
			if(actionList.size() > 0) {
				pollDTO.setFrequency(1000L);
				for(int i = 0; i < actionList.size(); i++) {
					if(actionList.get(i).getActionType() == Action.ACTION_TYPE_POLLING) {
						if(actionList.get(i).getTimeStamp().longValue() + pollEndingInterval < Calendar.getInstance().getTimeInMillis()) {
							pollDTO.setFrequency(5000L);
							actionList.remove(i);
							break;
						}
					}
				}
				pollDTO.setActionList(actionList);
			}
		}
		return gson.toJson(pollDTO);
	}
}
